export default {
  namespaced: true,
  state: () => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart')||'[]')
  }),
  mutations: {
    
    checkedAll(state){
      state.cart.forEach(x=>{
        if(!x.goods_state){
          x.goods_state=true
        }
      }),
      this.commit('m_cart/savetoStorage')
    },
    cancelCheckedAll(state){
      state.cart.forEach(x=>{
        if(x.goods_state){
          x.goods_state=false
        }
      }),
      this.commit('m_cart/savetoStorage')
    },
    addToCart(state, goods) {
      const findResult = state.cart.find(x => x.goods_id == goods.goods_id)
      if (findResult) {
        findResult.goods_count++
      } else {
        state.cart.push(goods)
      }
      this.commit('m_cart/savetoStorage')
    },
    updateGoodsState(state,goods){
      const findResult = state.cart.find(x => x.goods_id == goods.goods_id)
      if (findResult) {
        findResult.goods_state=goods.goods_state
      } 
      this.commit('m_cart/savetoStorage')
    },
    updateGoodsCount(state,goods){
      const findResult = state.cart.find(x => x.goods_id == goods.goods_id)
      if (findResult) {
        findResult.goods_count=goods.goods_count
      } 
      this.commit('m_cart/savetoStorage')
    },
    delectGoods(state,goods){
     state.cart= state.cart.filter(x => x.goods_id !== goods.goods_id)
      this.commit('m_cart/savetoStorage')
    },
    savetoStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    }
  },
  getters: {
    
    total(state) {
      let c = 0
      state.cart.forEach(x => c += x.goods_count)
      return c
    },
    getcheckednum(state){
      return state.cart.filter(x=>x.goods_state==true).reduce((total,item)=>total+=item.goods_count,0)
    },
    gettotalprices(state){
      return state.cart.filter(x=>x.goods_state==true).reduce((total,item)=>total+=(item.goods_count*item.goods_price),0)
    },
    checkedAllstate(state){
      return state.cart.every(x=>x.goods_state==true)
    }
  }
}
